package com.rr.middle;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author RR
 * @date 2022/10/17 23:09
 */
/*
* https://leetcode.cn/problems/fruit-into-baskets/
* 性能太差，有更好的解法，用双指针，需要重新写
* */
public class TotalFruit {
    public int totalFruit(int[] fruits) {
        int ans = 0;
        int index = 0;
        int tempAns = 0;
        int lastPosition = 0;
        Set<Integer> set = new HashSet<>();
        while (index < fruits.length) {
            if (set.add(fruits[index])) {
                if (set.size() > 2) {
                    ans = Math.max(ans, tempAns);
                    index = lastPosition;
                    tempAns = 0;
                    set.clear();
                }
                if (set.size() == 2) {
                    lastPosition = index;
                    index++;
                    tempAns++;
                }
            } else {
                index++;
                tempAns++;
            }
        }
        ans = Math.max(ans, tempAns);
        return ans;
    }
}
